package com.xudow.app.newui.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.activeshare.edu.ucenter.common.messages.user.UserDetailMessage;
import com.activeshare.edu.ucenter.models.user.UserCensus;
import com.activeshare.edu.ucenter.models.user.UserProfileWithOther;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.entity.UMessage;
import com.xudow.app.Config;
import com.xudow.app.R;
import com.xudow.app.dynamicstate_old.data.RongYunModel;
import com.xudow.app.dynamicstate_old.module.guide.ClazzActivity;
import com.xudow.app.dynamicstate_old.module.guide.RoleActivity;
import com.xudow.app.dynamicstate_old.module.user.AttentionListActivity;
import com.xudow.app.dynamicstate_old.module.user.UserDynamicListActivity;
import com.xudow.app.dynamicstate_old.module.user.UserProfileActivity;
import com.xudow.app.newui.PreLoginActivity;
import com.xudow.app.newui.RelatedParentActivity;
import com.xudow.app.newui.SettingActivity;
import com.xudow.app.newui.UserAgencyListActivity;
import com.xudow.app.newui.adapter.ChildsGridViewAdapter;
import com.xudow.app.newui.base.BaseUiFragment;
import com.xudow.app.newui.task.UserProfileTaskls;
import com.xudow.app.newui.zutils.SystemBarTintManager;
import com.xudow.app.ui.AddNewStudentActivity;
import com.xudow.app.ui.CartActivity;
import com.xudow.app.ui.CourseListActivity;
import com.xudow.app.ui.FeedbackActivity;
import com.xudow.app.ui.LoginActivity;
import com.xudow.app.ui.task.OrderListTask;
import com.xudow.app.ui.task.StudentListTask;
import com.xudow.app.ui.task.UserCensusTask;
import com.xudow.app.ui.task.UserProfileTask;
import com.xudow.app.ui.user.CouponsActivity;
import com.xudow.app.ui.user.FavoriteActivity;
import com.xudow.app.ui.user.OrdersActivity;
import com.xudow.app.util.ImageUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import de.hdodenhof.circleimageview.CircleImageView;
import rx.Subscription;
import rx.functions.Action1;

/**
 * 作者：zhouXJ on 2016/4/5 15:11
 * 我的
 */

public class ProfileFragment extends BaseUiFragment implements View.OnClickListener, AdapterView.OnItemClickListener {
    ChildsGridViewAdapter adapter;
    List<UserProfileWithOther> data;
    private String xuedouId = "";//学兜id
    UserProfileWithOther profile;//用户对象
    private UserCensus userCensus;//用户统计信息
    @BindView(R.id.profile_message_img)//私聊消息
            ImageView profile_message_img;

    @BindView(R.id.profile_setting_img)
    ImageView profile_setting_img;

    @BindView(R.id.profile_head_rl)
    RelativeLayout profile_head_rl;//用户头像布局

    @BindView(R.id.profile_dynamic_state_ll)
    LinearLayout profile_dynamic_state_ll;

    @BindView(R.id.profile_dynamic_state_tv)
    TextView profile_dynamic_state_tv;//动态数量

    @BindView(R.id.profile_attention_ll)
    LinearLayout profile_attention_ll;

    @BindView(R.id.profile_attention_tv)
    TextView profile_attention_tv;//关注数量

    @BindView(R.id.profile_fans_ll)
    LinearLayout profile_fans_ll;

    @BindView(R.id.profile_fans_tv)
    TextView profile_fans_tv;//粉丝数量

    @BindView(R.id.profile_course_ll)
    LinearLayout profile_course_ll;
    @BindView(R.id.profile_course_tv)
    TextView profile_course_tv;//课程数量

    @BindView(R.id.profile_order_ll)
    LinearLayout profile_order_ll;

    @BindView(R.id.profile_wait_payment_ll)
    LinearLayout profile_wait_payment_ll;

    @BindView(R.id.profile_over_payment_ll)
    LinearLayout profile_over_payment_ll;

    @BindView(R.id.payed_order_count_tv)
    TextView payed_order_count_tv;//已支付订单数

    @BindView(R.id.payed_order_count_rl)
    RelativeLayout payed_order_count_rl;

    @BindView(R.id.profile_wait_evaluate_ll)
    LinearLayout profile_wait_evaluate_ll;

    @BindView(R.id.profile_shopping_ll)
    LinearLayout profile_shopping_ll;

    @BindView(R.id.profile_fav_ll)
    LinearLayout profile_fav_ll;

    @BindView(R.id.profile_prefer_ll)
    LinearLayout profile_prefer_ll;

    @BindView(R.id.profile_feedback_ll)
    LinearLayout profile_feedback_ll;

    @BindView(R.id.childs_gv)
    GridView child_gv;//孩子列表

    @BindView(R.id.unpayed_order_count_tv)
    TextView unpayed_order_count_tv;//待付订单数量

    @BindView(R.id.user_gender_iv)
    ImageView user_gender_iv;//用户性别图标 btn_profile_sex_m/btn_profile_sex_w

    @BindView(R.id.user_ico_cv)//用户图标
            CircleImageView user_ico_cv;

    @BindView(R.id.user_name_tv)
    TextView user_name_tv;//用户姓名

    @BindView(R.id.agency_lable)//用户教师认证
            TextView agency_lable;

    @BindView(R.id.related_student_rl)
    RelativeLayout related_student_rl;//授权孩子

    @BindView(R.id.studyinfor_rl)
    RelativeLayout studyinfor_rl;//获取孩子学习信息

    @BindView(R.id.changestate_rl)
    RelativeLayout changestate_rl;//更改关注年级和心情

    @BindView(R.id.scrollview)
    ScrollView scrollview;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_profile, container, false);
    }

    Subscription subscription;

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        subscription = RongYunModel.getInstance().registerNotifyCount(new Action1<Integer>() {
            @Override
            public void call(Integer integer) {

                if (integer > 0) {
                    profile_message_img.setImageResource(R.mipmap.btn_profile_message1);
                } else {
                    profile_message_img.setImageResource(R.mipmap.btn_profile_message);
                }
            }
        });
        registerUmengMessage();
    }

    private void registerUmengMessage() {
        PushAgent.getInstance(getActivity()).setMessageHandler(new UmengMessageHandler() {
            @Override
            public void dealWithNotificationMessage(Context context, UMessage uMessage) {
                profile_message_img.setImageResource(R.mipmap.btn_profile_message1);
                super.dealWithNotificationMessage(context, uMessage);
            }

            @Override
            public void dealWithCustomMessage(Context context, UMessage uMessage) {
                super.dealWithCustomMessage(context, uMessage);
            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        retrieveUserProfile();//获取用户基本信息
        getStat();//加载用户统计信息
    }

    @Override
    public void onResume() {
        super.onResume();


        scrollview.fullScroll(ScrollView.FOCUS_UP);//滑到顶部
    }

    /**
     * 获取用户基本信息
     */
    private void retrieveUserProfile() {
        getMyAct().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                UserProfileTask userProfileTask = new UserProfileTask(getMyAct(),
                       userprofileHandler);
                userProfileTask.execute();
//                showLodingDialog("正在加载");

//                UserProfileTaskls userProfileTaskls=new UserProfileTaskls(getMyAct(),userprofileHandler);
//                userProfileTaskls.up();
            }
        });
    }

    /**
     * 用户基本信息Handler
     */
    private Handler userprofileHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();
            if (UserProfileTask.SUCCESS == msg.what) {
                Bundle data = msg.getData();
                UserDetailMessage ud = (UserDetailMessage) data.getSerializable("profile");
                profile = ud.getUserDetail();
                if (null != profile) {
                    getApp().setProfile(profile);
                    updataViewInfor();
                }
            } else {
                String message = msg.getData().getString("errMessage");
                if (null==message)
                    message="没获取到用户信息";
                getApp().makeToast(message);
            }
        }
    };


    /**
     * 设置用户头像
     *
     * @param portraitUrl
     */
    private void setPortrait(String portraitUrl) {
        String url = String.format("%s%s?name=%s", Config.BASE_URL, Config.IMAGE_LOAD_URL, portraitUrl);
        ImageUtils.loadImage(getMyAct(), user_ico_cv, url, R.mipmap.def_user_ico);

    }

    /**
     * 更新用户信息
     */
    private void updataViewInfor() {
        if (null != profile) {
            if (!TextUtils.isEmpty(profile.getNickName())) {
                user_name_tv.setText(profile.getNickName().trim());
                SharedPreferences.Editor sp = getActivity().getSharedPreferences("UserName",
                        getActivity().MODE_PRIVATE).edit();
                // 获取Editor对象

                sp.putString("Name", profile.getNickName().trim());
                sp.commit();
            }
            else{
                user_name_tv.setText(profile.getName());
                SharedPreferences.Editor sp = getActivity().getSharedPreferences("UserName",
                        getActivity().MODE_PRIVATE).edit();
                // 获取Editor对象

                sp.putString("Name", profile.getName());
                sp.commit();
            }


            if (null == profile.getGender()) {

                user_gender_iv.setVisibility(View.GONE);
            } else if (1 == profile.getGender()) {
                user_gender_iv.setImageResource(R.mipmap.btn_profile_sex_m);
            } else if (2 == profile.getGender()) {
                user_gender_iv.setImageResource(R.mipmap.btn_profile_sex_w);
            }
            if ("1".equals(profile.getIsAuthent()))//认证标记
                agency_lable.setVisibility(View.VISIBLE);
            else if ("0".equals(profile.getIsAuthent()))
                agency_lable.setVisibility(View.GONE);
            xuedouId = profile.getXuedouId();

            String portrait = profile.getPhotoPath();
            setPortrait(portrait);
        }
    }


    protected void initData() {
        adapter = new ChildsGridViewAdapter(getActivity(), null);
        data = new ArrayList<UserProfileWithOther>();
        /*retrieveUserProfile();//加载用户信息
        getStat();//加载用户统计信息*/


    }

    /**
     * 请求孩子列表
     */
    private void getChild() {

        StudentListTask getstudent = new StudentListTask(getActivity(), getstudentHandler);
        getMyAct().addTask(getstudent);
        getstudent.execute();
//        showLodingDialog("正在处理");
    }

    /**
     * 获取用户统计信息
     */
    private void getStat() {
        UserCensusTask censusTask = new UserCensusTask(getMyAct(), censusTaskHandler);
        getMyAct().addTask(censusTask);
        censusTask.execute();
//        showLodingDialog("正在加载");
    }

    /**
     * 获取用户统计信息Handler
     */
    private Handler censusTaskHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            hideLoadingDialog();
            if (OrderListTask.SUCCESS == msg.what) {
                userCensus = (UserCensus) msg.obj;
                if (null != userCensus) {
                    if (userCensus.getDynamicSize() >= 0)
                        profile_dynamic_state_tv.setText(userCensus.getDynamicSize() + "");
                    if (userCensus.getFollowSize() >= 0)
                        profile_attention_tv.setText(userCensus.getFollowSize() + "");
                    if (userCensus.getFansSize() >= 0)
                        profile_fans_tv.setText(userCensus.getFansSize() + "");
                    if (userCensus.getCourseSize() >= 0)
                        profile_course_tv.setText(userCensus.getCourseSize() + "");
                    if (userCensus.getToPaySize() > 0) {
                        unpayed_order_count_tv.setText(userCensus.getToPaySize() + "");
                        unpayed_order_count_tv.setVisibility(View.VISIBLE);
                    } else
                        unpayed_order_count_tv.setVisibility(View.GONE);
                    if (userCensus.getSuccessSize() > 0) {
                        payed_order_count_tv.setText(userCensus.getSuccessSize() + "");
                        payed_order_count_rl.setVisibility(View.VISIBLE);
                    } else
                        payed_order_count_rl.setVisibility(View.GONE);
                }
            }
        }
    };

    private Handler getstudentHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            hideLoadingDialog();
            if (msg.what == StudentListTask.SUCCESS) {

                Bundle bundle = msg.getData();
                UserProfileWithOther[] arr = (UserProfileWithOther[]) bundle.getSerializable("students");
                if (null != arr && arr.length > 0) {
                    data.clear();
                    data.addAll(Arrays.asList(arr));
                    adapter.setData(data);
                    child_gv.setAdapter(adapter);
                }
            } else
                getApp().makeToast("网络获取失败");
        }
    };

    @Override
    protected void initListener() {
        profile_message_img.setOnClickListener(this);
        profile_setting_img.setOnClickListener(this);
        profile_head_rl.setOnClickListener(this);
        profile_dynamic_state_ll.setOnClickListener(this);
        profile_attention_ll.setOnClickListener(this);
        profile_fans_ll.setOnClickListener(this);
        profile_course_ll.setOnClickListener(this);
        profile_order_ll.setOnClickListener(this);
        profile_wait_payment_ll.setOnClickListener(this);
        profile_over_payment_ll.setOnClickListener(this);
        profile_wait_evaluate_ll.setOnClickListener(this);
        profile_shopping_ll.setOnClickListener(this);
        profile_fav_ll.setOnClickListener(this);
        profile_prefer_ll.setOnClickListener(this);
        profile_feedback_ll.setOnClickListener(this);
        child_gv.setOnItemClickListener(this);
        changestate_rl.setOnClickListener(this);
        related_student_rl.setOnClickListener(this);
        studyinfor_rl.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        Intent intent;
        if (!getApp().isLogin()) {
            startActivity(new Intent(getContext(), PreLoginActivity.class));
            return;
        }
        switch (view.getId()) {

            case R.id.related_student_rl://授权

                    intent = new Intent(getMyAct(), RelatedParentActivity.class);
                    startActivity(intent);

                break;
            case R.id.studyinfor_rl://关联机构列表
                intent = new Intent(getMyAct(), UserAgencyListActivity.class);
                startActivity(intent);
                break;
            case R.id.profile_message_img: // 消息
                profile_message_img.setImageResource(R.mipmap.btn_profile_message);
                RongYunModel.getInstance().chatList(getContext());
                break;

            case R.id.profile_setting_img: // 设置
                intent = new Intent(getActivity(), SettingActivity.class);
                startActivity(intent);
                break;

            case R.id.profile_head_rl: // 个人详情

//                    intent = new Intent(getContext(), PreLoginActivity.class);
                if(profile!=null) {
                    intent = new Intent(getContext(), UserProfileActivity.class);
                    intent.putExtra(UserProfileActivity.USER_PROFILE_ID, profile.getId());

                    startActivity(intent);
                }
                break;

            case R.id.profile_dynamic_state_ll: // 动态

                if(profile!=null) {
                    Intent i4 = new Intent(getContext(), UserDynamicListActivity.class);
                    i4.putExtra("id", profile.getId());
                    startActivity(i4);
                }
                break;

            case R.id.profile_attention_ll: // 关注
                if(profile!=null) {
                    Intent i2 = new Intent(getContext(), AttentionListActivity.class);
                    i2.putExtra("isFans", false);
                    i2.putExtra("userId", profile.getId());
                    startActivity(i2);
                }
                break;

            case R.id.profile_fans_ll: // 粉丝
                if(profile!=null) {
                    Intent i3 = new Intent(getContext(), AttentionListActivity.class);
                    i3.putExtra("isFans", true);
                    i3.putExtra("userId", profile.getId());
                    startActivity(i3);
                }
                break;

            case R.id.profile_course_ll: // 课兜
                intent = new Intent(getContext(), CourseListActivity.class);
                intent.putExtra("mode", "mycourselist");
                startActivity(intent);
                break;

            case R.id.profile_order_ll: // 订单
                intent = new Intent(getContext(), OrdersActivity.class);
                startActivity(intent);
                break;

            case R.id.profile_wait_payment_ll: // 待付款
                intent = new Intent(getContext(), OrdersActivity.class);
                intent.putExtra("orderstate", 2);
                startActivity(intent);
                break;

            case R.id.profile_over_payment_ll: // 已付款
                intent = new Intent(getContext(), OrdersActivity.class);
                intent.putExtra("orderstate", 0);
                startActivity(intent);
                break;

            case R.id.profile_shopping_ll: // 购物车
                intent = new Intent(getContext(), CartActivity.class);
                startActivity(intent);
                break;

            case R.id.profile_fav_ll: // 收藏
                intent = new Intent(getContext(), FavoriteActivity.class);
                startActivity(intent);
                break;

            case R.id.profile_prefer_ll: // 优惠券
                intent = new Intent(getContext(), CouponsActivity.class);
                startActivity(intent);
                break;

            case R.id.profile_feedback_ll: // 在线投诉
                intent = new Intent(getContext(), FeedbackActivity.class);
                startActivity(intent);
                break;

            case R.id.changestate_rl://更改关注年级和兴趣
                intent = new Intent(getContext(), ClazzActivity.class);
                intent.putExtra("isLogin", true);
                startActivity(intent);

                break;

        }
    }

    /**
     * 孩子gv 监听
     *
     * @param parent
     * @param view
     * @param position
     * @param id
     */
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == data.size()) {
            getApp().makeToast("添加孩子");
            startActivity(new Intent(getActivity(), AddNewStudentActivity.class));
        } else {
            getApp().makeToast(data.get(position).getName());
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (subscription != null) {
            subscription.unsubscribe();
        }
    }
}
